﻿using AntdUI;
using Serilog;
using System.Text;
using WorkTool2.Helpers;
using WorkTool2.Interfaces;

namespace WorkTool2.Controls
{
    public partial class AppSettings : UserControl, IReload
    {
        private readonly string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "appsettings.json");

        private Form form;

        public AppSettings(Form _form)
        {
            form = _form;
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            ITask.Run(() =>
            {
                richTextBox.InvokeIfRequired(() =>
                {
                    InitRichTextBox();
                });
                Reload();
            });
        }

        #region RichTextBox

        private Color borderColorUnFocusWhite = Color.FromArgb(220, 220, 220);
        private Color borderColorUnFocusBlack = Color.FromArgb(40, 40, 40);
        private Color borderColorFocusWhite = Color.FromArgb(160, 200, 255);
        private Color borderColorFocusBlack = Color.FromArgb(50, 89, 158);

        private void InitRichTextBox()
        {
            SettingColor();
            richTextBox_ClearBtn.Hide();
            richTextBox.MouseEnter += FocusColor;
            richTextBox.MouseLeave += UnFocusColor;
            richTextBox.GotFocus += (s, e) =>
            {
                FocusColor(s, e);
                richTextBox.MouseLeave -= UnFocusColor;
            };
            richTextBox.Leave += (s, e) =>
            {
                UnFocusColor(s, e);
                richTextBox.MouseLeave += UnFocusColor;
            };
            richTextBox.Resize += (s, e) =>
            {
                UpdateClearButtonPosition();
            };
            UpdateClearButtonPosition();
            form.ForeColorChanged += (s, e) =>
            {
                SettingColor();
            };
        }

        private void SettingColor()
        {
            if (Config.IsDark)
            {
                richTextBox.BackColor = Color.Black;
                richTextBox.ForeColor = Color.White;
                richTextBox_ClearBtn.OriginalBackColor = Color.Black;
                richTextBox_Border.BackColor = borderColorUnFocusBlack;
            }
            else
            {
                richTextBox.BackColor = Color.White;
                richTextBox.ForeColor = Color.Black;
                richTextBox_ClearBtn.OriginalBackColor = Color.White;
                richTextBox_Border.BackColor = borderColorUnFocusWhite;
            }
        }

        private void FocusColor(object? s, EventArgs e)
        {
            richTextBox_ClearBtn.Show();
            richTextBox_Border.BackColor = Config.IsDark ? borderColorFocusBlack : borderColorFocusWhite;
        }

        private void UnFocusColor(object? s, EventArgs e)
        {
            richTextBox_ClearBtn.Hide();
            richTextBox_Border.BackColor = Config.IsDark ? borderColorUnFocusBlack : borderColorUnFocusWhite; // 边框颜色
        }

        private void UpdateClearButtonPosition()
        {
            richTextBox_ClearBtn.Location = new Point(
                richTextBox_Border.Right - richTextBox_ClearBtn.Width - 20,
                richTextBox_Border.Top + 4
            );
            richTextBox_ClearBtn.BringToFront();
        }

        private void richTextBox_ClearBtn_Click(object sender, EventArgs e)
        {
            richTextBox.Clear();
            richTextBox.Invalidate();
            richTextBox.Focus();
            richTextBox.MouseLeave -= UnFocusColor;
        }

        #endregion

        public void Reload()
        {
            Task.Run(async () =>
            {
                try
                {
                    var text = await File.ReadAllTextAsync(filePath);
                    richTextBox.InvokeIfRequired(() =>
                    {
                        richTextBox.Text = text.Trim();
                        _oldSettingsText = text.Trim();
                        richTextBox.Select(0, 0);
                    });
                }
                catch (Exception ex)
                {
                    new Modal.Config(form, "配置文件加载失败", ex.Message, TType.Error)
                    {
                        CancelText = null,
                        OkType = TTypeMini.Error,
                        OkText = "知道了"
                    }.open();
                    Log.Error(ex, ex.Message);
                }
            }).Wait();
        }

        private string _oldSettingsText = string.Empty;

        public void Save()
        {
            Spin.open(form, "正在处理中，请耐心等候...",
                 config =>
                 {
                     Task.Run(async () =>
                     {
                         Thread.Sleep(500);
                         var settings = string.Empty;
                         richTextBox.InvokeIfRequired(() =>
                         {
                             settings = richTextBox.Text.Trim();
                         });
                         if (string.IsNullOrEmpty(settings))
                         {
                             Modal.open(form, "错误", "配置不能为空", TType.Error);
                             return;
                         }
                         var result = JsonValidationHelper.ValidateJsonWithComments(settings);
                         if (!result.IsValid)
                         {
                             Modal.open(form, "错误", result.Error, TType.Error);
                             return;
                         }
                         try
                         {
                             await File.WriteAllTextAsync(filePath, settings, Encoding.UTF8);
                             Notification.success(form, "保存成功", "", AntdUI.TAlignFrom.Top);
                         }
                         catch (Exception ex)
                         {
                             Notification.error(form, "保存失败", ex.Message, AntdUI.TAlignFrom.Top);
                             Log.Error(ex, ex.Message);
                         }
                     }).Wait();
                 },
                 () => { }
             );
        }

        public void Reset()
        {
            Spin.open(form, "正在处理中，请耐心等候...",
                 config =>
                 {
                     Task.Run(async () =>
                     {
                         Thread.Sleep(500);
                         try
                         {
                             richTextBox.Text = await File.ReadAllTextAsync(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "appsettings.Template.json"));
                             richTextBox.Select(0, 0);
                             Notification.success(form, "重置成功", "", AntdUI.TAlignFrom.Top);
                         }
                         catch (Exception ex)
                         {
                             Notification.error(form, "重置失败", ex.Message, AntdUI.TAlignFrom.Top);
                             Log.Error(ex, ex.Message);
                         }
                     }).Wait();
                 },
                 () => { }
             );
        }

        public void Rollback()
        {
            Spin.open(form, "正在处理中，请耐心等候...",
                config =>
                {
                    Thread.Sleep(500);
                    try
                    {
                        richTextBox.Text = _oldSettingsText;
                        richTextBox.Select(0, 0);
                        Notification.success(form, "撤销成功", "", AntdUI.TAlignFrom.Top);
                    }
                    catch (Exception ex)
                    {
                        Notification.error(form, "撤销失败", ex.Message, AntdUI.TAlignFrom.Top);
                        Log.Error(ex, ex.Message);
                    }
                },
                () => { }
            );
        }
    }
}